package servlet;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.quartz.JobDetail;
import org.quartz.JobKey;
import org.quartz.Scheduler;
import org.quartz.Trigger;
import org.quartz.TriggerKey;
import org.quartz.impl.StdSchedulerFactory;
import org.quartz.impl.matchers.GroupMatcher;

import coreJob.Core;
import coreJob.common.Tool;

public class ControlServlet extends HttpServlet {
	Logger log = Logger.getLogger(ControlServlet.class);
	private static final long serialVersionUID = 1L;

	public void doGet(HttpServletRequest request, HttpServletResponse response) {
		try {
			String uri = request.getRequestURI();
			if (uri.lastIndexOf("/") < uri.lastIndexOf(".")) {
				//获取请求路径
				String path = uri.substring(uri.lastIndexOf("/"), uri
						.lastIndexOf("."));
				//获取jobName 参数
				String name=null;
				if(request.getParameter("jobName")!=null){
				    name = new String(request.getParameter("jobName").getBytes("iso8859-1"), "utf-8");
				}
				//获取jobGroup 参数
				String group=null;
				if(request.getParameter("jobGroup")!=null){
					group = new String(request.getParameter("jobGroup").getBytes("iso8859-1"),"utf-8"); 
				}
				
				if(path.equals("/index")){
					//请求主页数据 //系统正常访问主页
					index(request, response);
					return;
				}else if(path.equals("/refreshJob")){
					//刷新任务，重新加载Class
					refreshJob();
				}else if((Tool.isNotEmpty(name) && Tool.isNotEmpty(group))){
					//参数正常的情况下，访问如下接口
					if (path.equals("/pauseJob")) {//暂停
						pauseJob(name, group);
					} else if (path.equals("/resumeJob")) {
						resumeJob(name, group);
					} else if (path.equals("/moreoneJob")) {
						moreoneJob(name, group);
					} else if(path.equals("/refreshJob")){
						refreshJob();
					} else if(path.equals("/deleteJob")){
						deleteJob(name, group);
					} else if(path.equals("/startJobNow")){
						startJobNow(name, group);
					} else if(path.equals("/reSetRule")){
						String ruleType = new String(request.getParameter("ruleType").getBytes("iso8859-1"),"utf-8"); 
						String cronExpression = new String(request.getParameter("cronExpression").getBytes("iso8859-1"),"utf-8"); 
						String cronDescription = new String(request.getParameter("cronDescription").getBytes("iso8859-1"),"utf-8"); 
						String errorMsg=reSetRule(name, group,Integer.parseInt(ruleType),cronExpression,cronDescription);
						if(errorMsg!=null){
							response.sendRedirect("index.html?errorMsg=1");//返回主页
						}
					}
				}
			}
				response.sendRedirect("index.html");//返回主页
			
			
		} catch (Exception exception) {
			exception.printStackTrace();
		}
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		this.doGet(request, response);
	}

	private void index(HttpServletRequest request, HttpServletResponse response) {
		try {
			SimpleDateFormat format = new SimpleDateFormat(
					"yyyy-MM-dd HH:mm:ss");
			String statisticsDate = format.format(new Date());
			request.setAttribute("statisticsDate", statisticsDate);

			Scheduler scheduler = StdSchedulerFactory.getDefaultScheduler();
			GroupMatcher<JobKey> matcher = GroupMatcher.anyJobGroup();
			Set<JobKey> jobKeys = scheduler.getJobKeys(matcher);
			List<Map<String, String>> jobList = new ArrayList<Map<String, String>>();
			for (JobKey jobKey : jobKeys) {
				List<? extends Trigger> triggers = scheduler
						.getTriggersOfJob(jobKey);
				for (Trigger trigger : triggers) {
					Map<String, String> map = new HashMap<String, String>();
					Trigger.TriggerState triggerState = scheduler
							.getTriggerState(trigger.getKey());
					map.put("state", triggerState.name()); // 任务状态
					map.put("jobName", jobKey.getName());

					map.put("jobGroup", jobKey.getGroup());
					if (trigger.getNextFireTime() == null
							|| !triggerState.name().equals("NORMAL")) {
						map.put("nextFireTime", "-");
						map.put("During", "-");
					} else {
						map.put("nextFireTime", format.format(trigger
								.getNextFireTime()));
						map.put("During", Tool.formatDuring(trigger
								.getNextFireTime().getTime()
								- new Date().getTime()));
					}
					map.put("preFrieTime","-");
					if(trigger.getPreviousFireTime()!=null){
						map.put("preFrieTime", format.format(trigger
								.getPreviousFireTime()));
					}
					map.put("description", trigger.getDescription());
					map.put("startTime", format.format(trigger.getStartTime()));

					jobList.add(map);
				}
			}

			request.setAttribute("jobList", jobList);
			request.setAttribute("errorMsg", request.getParameter("errorMsg"));
			request.getRequestDispatcher("index.jsp").forward(request, response);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	private void pauseJob(String name,String group) {
		try {
			if (name != null && group != null) {		
				JobKey jobKey = JobKey.jobKey(name, group);
				Scheduler scheduler = StdSchedulerFactory.getDefaultScheduler();
				scheduler.pauseJob(jobKey);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	private void resumeJob(String name,String group) {
		try {
			
			if (name != null && group != null) {
				JobKey jobKey = JobKey.jobKey(name, group);
				Scheduler scheduler = StdSchedulerFactory.getDefaultScheduler();
				scheduler.resumeJob(jobKey);
				
			}
			
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	private void moreoneJob(String name,String group) {
		try {
			if (name != null && group != null) {
				JobKey jobKey = JobKey.jobKey(name, group);
				Scheduler scheduler = StdSchedulerFactory.getDefaultScheduler();
				scheduler.triggerJob(jobKey);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	private void refreshJob() {
		try {
			Core core=new Core();
			core.initJob();
		}catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	private void deleteJob(String name,String group){
		try {
			Scheduler scheduler = StdSchedulerFactory.getDefaultScheduler();
			JobKey jobKey = JobKey.jobKey(name, group);
			//scheduler.deleteJob(jobKey);
			pauseJob(name, group);
			scheduler.unscheduleJob(TriggerKey.triggerKey(name, group));
			scheduler.deleteJob(jobKey);
			
		
			
		}catch (Exception e) {
			e.printStackTrace();
		}
	}
	/**
	 * 立即执行调度
	 * @param name
	 * @param group
	 */
	private void startJobNow(String name,String group){
		try {
			Scheduler scheduler = StdSchedulerFactory.getDefaultScheduler();
			JobKey jobKey = JobKey.jobKey(name, group);
            Trigger trigger=scheduler.getTriggersOfJob(jobKey).get(0);
			Trigger triggerTemp=scheduler.getTriggersOfJob(jobKey).get(0).getTriggerBuilder().withIdentity(trigger.getKey()).startNow().build();
			JobDetail  jobDetail=scheduler.getJobDetail(jobKey);

			pauseJob(name, group);
			scheduler.unscheduleJob(TriggerKey.triggerKey(name, group));
			scheduler.deleteJob(jobKey);
			
			scheduler.scheduleJob(jobDetail, triggerTemp);
		}catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * 重新设置调度规则
	 * @param name
	 * @param group
	 * @param ruleType
	 * @param cronText
	 * @param cronDescription
	 */
	@SuppressWarnings({ "unchecked", "static-access" })
	private String reSetRule(String name,String group,int ruleType,String cronString,String cronDescription){
		try {
			Scheduler scheduler = StdSchedulerFactory.getDefaultScheduler();
			JobKey jobKey = JobKey.jobKey(name, group);
			JobDetail  jobDetail=scheduler.getJobDetail(jobKey);
			
          
            Trigger tempTrigger=null;         
            if(ruleType==1){
            	//每分钟
            	tempTrigger=Tool.getMinutelyTrigger(null);
            }else if(ruleType==2){
            	//每小时
            	tempTrigger=Tool.getHourlyTrigger(null); 
            }else if(ruleType==3){
            	//每天
            	tempTrigger=Tool.getDaylyTrigger(null);
            }else if(ruleType==0){
            	//自定义Cron
            	try{
            	tempTrigger=Tool.getCronTrigger(null, cronString, cronDescription == null ? "按Cron【"+cronString+"】计划执行,此Job没有配置Cron说明" : cronDescription);
            	}catch (Exception e) {
            		log.error("配置的Cron表达式错误，请重新填写",e);
            		return "配置的Cron表达式错误，请重新填写";
				}
            }
            pauseJob(name, group);
			scheduler.unscheduleJob(TriggerKey.triggerKey(name, group));
			scheduler.deleteJob(jobKey);
			
			scheduler.scheduleJob(jobDetail, tempTrigger);
			
		}catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
}
